//
//  STTools_LocationManger.m
//  KunLun
//
//  Created by coder on 2017/11/29.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "STTools_LocationManger.h"
#define STTools_Last_location @"STTools_Last_location"
@interface STTools_LocationManger()<CLLocationManagerDelegate>
@property(nonatomic,strong) CLLocationManager               *locationManger;
@property(nonatomic,copy) STTools_LocationMangerDidLocation_stoneobs_handle       handle;
@end

@implementation STTools_LocationManger
+ (STTools_LocationManger *)defult{
    static STTools_LocationManger * stoneobs_temp_defult = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        stoneobs_temp_defult = [STTools_LocationManger new];
    });
    return stoneobs_temp_defult;
}
- (CLLocationManager *)locationManger{
    if (!_locationManger) {
        _locationManger = [CLLocationManager new];
        _locationManger.delegate = self;
        _locationManger.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManger.distanceFilter = 100.0f;
    }
    return _locationManger;
}
- (NSDictionary *)stoneobs_fun_lastPlacemark{
    NSDictionary *stoneobs_temp_dic = [[NSUserDefaults standardUserDefaults] dictionaryForKey:STTools_Last_location];
    if (!stoneobs_temp_dic) {
        NSLog(@"您未调用stoneobs_fun_st_updatePlacemarkWith，没有储存地址");
    }
    return stoneobs_temp_dic;
}
- (NSString *)stoneobs_fun_st_lastProvence{
    NSDictionary * stoneobs_temp_dic = [[NSUserDefaults standardUserDefaults] dictionaryForKey:STTools_Last_location];
    if (!stoneobs_temp_dic) {
        NSLog(@"您未调用stoneobs_fun_st_updatePlacemarkWith，没有储存地址");
    }
    return stoneobs_temp_dic[@"administrativeArea"];
}
- (NSString *)stoneobs_fun_st_lastCity{
    NSDictionary * stoneobs_temp_dic = [[NSUserDefaults standardUserDefaults] dictionaryForKey:STTools_Last_location];
    if (!stoneobs_temp_dic) {
        NSLog(@"您未调用stoneobs_fun_st_updatePlacemarkWith，没有储存地址");
    }
    return stoneobs_temp_dic[@"locality"];
}
- (NSString *)stoneobs_fun_st_lastSubLocality{
    NSDictionary * stoneobs_temp_dic = [[NSUserDefaults standardUserDefaults] dictionaryForKey:STTools_Last_location];
    if (!stoneobs_temp_dic) {
        NSLog(@"您未调用stoneobs_fun_st_updatePlacemarkWith，没有储存地址");
    }
    return stoneobs_temp_dic[@"subLocality"];
}
- (void)stoneobs_fun_st_updatePlacemarkWith:(CLPlacemark *)lastPalcemark{
    if (lastPalcemark &&
        lastPalcemark.locality.length &&
        lastPalcemark.subLocality.length) {
        NSString * administrativeArea = lastPalcemark.administrativeArea;
        administrativeArea = administrativeArea.length?administrativeArea:@"";
        //如果是直辖市，那么省为空，接口province字段传@“”，可以获取到数据
        NSDictionary *stoneobs_temp_dic = @{@"administrativeArea":administrativeArea,
                              @"locality":lastPalcemark.locality,
                              @"subLocality":lastPalcemark.subLocality};
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:STTools_Last_location];
        [[NSUserDefaults standardUserDefaults] setObject:stoneobs_temp_dic forKey:STTools_Last_location];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}
- (void)dealAuthorization{
    CLAuthorizationStatus stoneobs_temp_status = [CLLocationManager authorizationStatus];
    if (stoneobs_temp_status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        [self.locationManger startUpdatingLocation];
    } else{
        [self dealErrorAuthorization];
    }
}
- (void)dealErrorAuthorization{
    CLAuthorizationStatus stoneobs_temp_status =  [CLLocationManager authorizationStatus];
    if (stoneobs_temp_status == kCLAuthorizationStatusRestricted) {
        NSString * stoneobs_temp_desc = @"定位：定位服务授权状态是受限制的";
        STTools_Error * stoneobs_temp_error = [[STTools_Error alloc] initWithCode:22222 andDesc:stoneobs_temp_desc];
        NSLog(@"status = kCLAuthorizationStatusRestricted%@",stoneobs_temp_error.desc);
        if (self.handle) {
            self.handle(stoneobs_temp_error, nil);
        }
    }else if (stoneobs_temp_status == kCLAuthorizationStatusDenied) {
        NSString * stoneobs_temp_desc = @"定位：定位服务授权状态已经被用户明确禁止，或者在设置里的定位服务中关闭";
        STTools_Error * stoneobs_temp_error = [[STTools_Error alloc] initWithCode:22222 andDesc:stoneobs_temp_desc];
        NSLog(@"status = kCLAuthorizationStatusDenied %@",stoneobs_temp_desc);
        if (self.handle) {
            self.handle(stoneobs_temp_error, nil);
        }
    }
}
/**
 开始定位，未获取权限则请求权限
 
 @param handel handel description
 */
- (void)stoneobs_fun_st_startUpdatingLocationHande:(STTools_LocationMangerDidLocation_stoneobs_handle)handel{
    [self setHandle:handel];
    CLAuthorizationStatus stoneobs_temp_status =  [CLLocationManager authorizationStatus];
    if (stoneobs_temp_status == kCLAuthorizationStatusNotDetermined) {
        NSLog(@"定位：用户还未做出选择");
        //开始请求权限
        [self.locationManger requestWhenInUseAuthorization];
    }else{
        if (stoneobs_temp_status == kCLAuthorizationStatusAuthorizedWhenInUse) {
            [self.locationManger startUpdatingLocation];
        }else{
            [self dealErrorAuthorization];
        }
    }
}
#pragma mark --CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    [self dealAuthorization];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *stoneobs_temp_newLocation = locations[0];
    CLLocationCoordinate2D stoneobs_temp_oldCoordinate = stoneobs_temp_newLocation.coordinate;
    [manager stopUpdatingLocation];
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:stoneobs_temp_newLocation completionHandler:^(NSArray<CLPlacemark *> *_Nullable placemarks, NSError * _Nullable error) {
        for (CLPlacemark *place in placemarks) {
            self.currentPlacemark = place;
            if (self.handle) {
                NSLog(@"经度：%f,纬度：%f", stoneobs_temp_oldCoordinate.longitude, stoneobs_temp_oldCoordinate.latitude);
                self.longitude = [NSString stringWithFormat:@"%f",stoneobs_temp_oldCoordinate.longitude];
                self.latitude = [NSString stringWithFormat:@"%f",stoneobs_temp_oldCoordinate.latitude];
                self.handle(nil,place);
                //方法多次调用，防止多次回调
                [self setHandle:nil];
            }
            //            NSLog(@"name,%@",place.name);                      // 位置名
            //            NSLog(@"thoroughfare,%@",place.thoroughfare);      // 街道
            //            NSLog(@"subThoroughfare,%@",place.subThoroughfare);// 子街道
            //            NSLog(@"locality,%@",place.locality);              // 市
            //            NSLog(@"subLocality,%@",place.subLocality);        // 区
            //            NSLog(@"country,%@",place.country);                // 国家
        }
    }];
}
- (void)locationManager:(CLLocationManager *)manager rangingBeaconsDidFailForRegion:(nonnull CLBeaconRegion *)region withError:(nonnull NSError *)error{
    if (manager == self.locationManger && error) {
        NSString * stoneobs_temp_desc = error.description;
        STTools_Error * stoneobs_temp_error = [[STTools_Error alloc] initWithCode:22222 andDesc:stoneobs_temp_desc];
        if (self.handle) {
            self.handle(stoneobs_temp_error,nil);
        }
    }
}


@end
